<?php

$loader->requireOnce('includes/RadConnector/InPatientRadConnector.class.php');
$loader->requireOnce('includes/RadConnector/OutPatientRadConnector.class.php');
$loader->requireOnce('includes/RadProcessor/EndoscopyProcessor.class.php');
$loader->requireOnce('controllers/C_RadResult.class.php');
class C_Endoscopy extends Controller {
    private $logger ;

    function __construct($template_mod = "general") {
        parent::__construct($template_mod);
        $this->logger = LoggerManager::getLogger('module.dept_rad.controllers.C_Endoscopy');
        $this->template_mod = $template_mod;
        $this->view->path="endoscopy";
    }

    public function actionGetServicesByGroupAjax($groupId = 0, $ticketId = 0) {
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL,'mess'=>''), 'result'=>'');
    	if (isset($_GET['groupId'])) {
            $groupId    =   $_GET['groupId'];
        }
        if (isset($_GET['ticketId'])) {
            $ticketId    =   $_GET['ticketId'];
        }
        $this->logger->info('Start action GetServicesByGroupAjax');
        $serviceList    =   ORDataObject::factory('RadService')->getServicesByGroup($groupId);
        $options        =   '';
        foreach ($serviceList as $key=>$value) {
            $prices    =   ORDataObject::factory('Service')->getPrices($ticketId, $key, EnumerationConstant::SER_INS_ITEM_TYPE_PTTT);
            $options    .=  "<option value=\"$key\" label=\"$value\" price=\"" . $prices['price'].
                            "\" insprice=\"" . $prices['insurance_price'] .
                            "\" patprice=\"" . $prices['patient_price'] . "\">$value</option>";
        }
        $result['result']   =   $options;
        $this->logger->info('Finish action GetServicesByGroupAjax');

        return json_encode($result);
    }

    /**
     * Save a radiology assignment ticket
     *
     * @return array Result array of structure ('error'=>array, 'result'=>data)
     */
    public function actionSaveAssignmentTicketAjax() {
        $result = array('error'=>array('code'=>CoreErrorCode::NORMAL, 'mess'=>''), 'result'=>'');
        $this->logger->info('Start action saveAssignmentTicketAjax {ticketId='. $_POST['ticketId'] . '}');
        try {
        $ticketId   =   $_POST['ticketId'];
        // Patient type
        $objTicket  =   Celini::newORDO('Ticket', $ticketId);
        $enumPatientType    =   $objTicket->getEnumPatientType();


        if ($enumPatientType == Utils::getEnumKey(EnumerationConstant::PATIENT_TYPE, EnumerationConstant::PATIENT_TYPE_INPATIENT)){
            // Initiate InPatientRadConnector
            $objRadConnector    =   new InPatientRadConnector();
        }
        else {
            // Inniate OutPatientRadConnector
            $objRadConnector    =   new OutPatientRadConnector();
        }

        // HIS: Do before create radiology assigment ticket
        $objRadConnector->doBeforeCreateAssignment();

        // RIS: Create assignment ticket
        $_POST['departmentId']  =   $this->_me->get_department_id();
        $objProcessor   =   new EndoscopyProcessor(Utils::getEnumKey(EnumerationConstant::PARACLINIC_TYPE, EnumerationConstant::PARACLINIC_ENDO));
        $data           =   $objProcessor->saveAssignmentTicket($_POST);

        // HIS: Do after create assigment ticket
        // Room Id and Payment type of the radiology type
        $info   =    ORDataObject::factory('ParacliniqueConfig')->getParaclinicConfig(EnumerationConstant::PARACLINIC_ENDO);
        $data['ticketId']=   $ticketId;
        $data['radType']=   $_POST['radType'];
        $data['roomId'] =   $info['room_id'];
        $data['paymentType']    =   $info['enum_payment_type'];
        $objRadConnector->doAfterCreateAssignment($data);
        }
        catch (HISFileLoaderException $e) {
            $result['error']['code'] = CoreErrorCode::LOAD_RAD_MODULE_FAIL;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::LOAD_RAD_MODULE_FAIL);
            $this->logger->error("Action saveAssignmentTicketAjax fail. Error:" . $e->getMessage());
        }
        catch (Exception $e) {
            $result['error']['code'] = CoreErrorCode::COMMON_ERROR;
            $result['error']['mess'] = CoreErrorCode::getErrorMess(CoreErrorCode::COMMON_ERROR);
            $this->logger->error("Action saveAssignmentTicketAjax fail. Error:" . $e->getMessage());
        }
        $this->logger->info('Finish action saveAssignmentTicketAjax {ticketId='. $_POST['ticketId'] . '}');

        return json_encode($result);
    }

    public function actionGetItemResultAjax($radTicketItemId = 0) {
        $radTicketItemId    =   EnforceType::int($_GET['radTicketItemId']);
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $objTicketItem  =   Celini::newORDO('RadTicketItem', $radTicketItemId);
        $objService     =   Celini::newORDO('Service', $objTicketItem->getServiceId());
        $result['result']['serviceName']    =   $objService->getLocalizedText('name');
        $radTicketId    =   $objTicketItem->getRadTicketId();
        $enumRadType    =   Celini::newORDO('RadTicket', $radTicketId)->getEnumRadType();
        // Meta data
        $objMeta    =  ORDataObject::factory('RadResultMeta')->getObjectByTicketItem($radTicketItemId);
        $result['result']['doctorId']      =     $objMeta->getDoctorId();
        $result['result']['technician1']   =     $objMeta->getTechnicianId1();
        $result['result']['technician2']   =     $objMeta->getTechnicianId2();
        $result['result']['description']   =     html_entity_decode($objMeta->getDescription());
        $result['result']['conclusion']    =     html_entity_decode($objMeta->getConclusion());
        $result['result']['machineName']   =     $objMeta->getMachineName();
        $result['result']['additionalService']   =     $this->buildAdditionalServiceBlock($enumRadType, $radTicketItemId);
        $createdArr =   explode(" ", $objMeta->get('created'));
        $objDate    =   DateObject::createFromISO($createdArr[0]);
        $result['result']['created_dd']    =   $objDate->getDay();
        $result['result']['created_mm']    =   $objDate->getMonth();
        $result['result']['created_yyyy']  =   $objDate->getYear();
        $result['result']['createdTime']   =    L10nHelper::renderDateTime($objMeta->get('created'), null, 'time');

        $ctlRadResult   =   new C_RadResult();
        $result['result']['radImage']      =    $ctlRadResult->getRadImageHTML($radTicketItemId);

        return json_encode($result);
    }

    private function buildAdditionalServiceBlock($enumRadType, $radTicketItemId, $viewMode = false) {
        $radTypeAddServiceList  =   ORDataObject::factory('RadAdditionalService')->getServicesByType($enumRadType);
        $itemAddServiceList     =   ORDataObject::factory('RadAdditionalServiceItem')->getServicesByTicketItem($radTicketItemId);
        $html   =   '';
        if ($viewMode) {
            $disable   =   "disabled=\"disabled\"";
        }
        else {
            $disable   =   '';
        }
        foreach ($radTypeAddServiceList as $key => $name) {
            if (in_array($key, $itemAddServiceList)) {
                $html   .=   "<input type=\"checkbox\" value='$key' name=\"additionalServices[]\" checked='checked' $disable/>" .
                            "<span>" . $name . "</span><br/>";
            }
            else {
                $html   .=   "<input type=\"checkbox\" value='$key' name=\"additionalServices[]\" $disable/>" .
                            "<span>" . $name . "</span><br/>";
            }
        }

        return $html;
    }

    public function actionSaveMetaDataAjax(){
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $radTicketItemId    =   EnforceType::int($_POST['radTicketItemId']);
        $this->logger->info("Start action SaveMetaDataAjax {radTicketItemId=$radTicketItemId}");
        $objResultData      =   ORDataObject::factory('RadResultMeta')->getObjectByTicketItem($radTicketItemId);
        $machince           =   Utils::sanitizeText($_POST['machine']);
        $description        =   Utils::sanitizeText($_POST['description'], false);
        $conclusion         =   Utils::sanitizeText($_POST['conclusion'], false);
        $created['day']     =   Utils::sanitizeText($_POST['created_dd']);
        $created['month']   =   Utils::sanitizeText($_POST['created_mm']);
        $created['year']    =   Utils::sanitizeText($_POST['created_yyyy']);
        $createdTime        =   L10nHelper::getISODate($created) . " " . Utils::sanitizeText($_POST['createdTime']);
        // Set data to object
        $objResultData->setData($radTicketItemId, $_POST['doctorId'], $_POST['technicianId1'], $_POST['technicianId2'],
            $machince, $description, $conclusion, $createdTime);
        $objResultData->persist();

        // Additional services
        // Delete all existing additonal services of the item
        ORDataObject::factory('RadAdditionalServiceItem')->deleteByTicketItem($radTicketItemId);
        if (isset($_POST['additionalServices'])) {
            $i  =   0;
            while (isset($_POST['additionalServices'][$i])) {
                $addServiceId   =   $_POST['additionalServices'][$i];
                $objAddService  =   Celini::newORDO('RadAdditionalService', $addServiceId);
                $objAddItem     =   Celini::newORDO('RadAdditionalServiceItem');
                $objAddItem->setData($radTicketItemId, $addServiceId, $objAddService->getPrice());
                $objAddItem->persist();
                $i++;
            }
        }

        // Update status of rad_ticket_item to done
        $objRadItem =   ORDataObject::factory('RadTicketItem');
        $objRadItem->updateItemStatus($radTicketItemId, 1);
        $info   = $objRadItem->getItemInfo($radTicketItemId);
        $result['result']['itemId']     =   $radTicketItemId;
        $result['result']['itemName']   =   RadUtils::generateRadItemName($info[0]['name'], $info[0]['is_done']);
        $this->logger->info("Finish action SaveMetaDataAjax {radTicketItemId=$radTicketItemId}");

        return json_encode($result);
    }

    public function actionGetItemResultViewAjax($radTicketItemId = 0) {
        $radTicketItemId    =   EnforceType::int($_GET['radTicketItemId']);
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $objTicketItem  =   Celini::newORDO('RadTicketItem', $radTicketItemId);
        $objService     =   Celini::newORDO('Service', $objTicketItem->getServiceId());
        $result['result']['serviceName']    =   $objService->getLocalizedText('name');
        $radTicketId    =   $objTicketItem->getRadTicketId();
        $enumRadType    =   Celini::newORDO('RadTicket', $radTicketId)->getEnumRadType();
        // Meta data
        $objMeta    =  ORDataObject::factory('RadResultMeta')->getObjectByTicketItem($radTicketItemId);
        $result['result']['doctorName']    =     Celini::newORDO('Person', $objMeta->getDoctorId())->getName();
        $result['result']['technician1']   =     Celini::newORDO('Person', $objMeta->getTechnicianId1())->getName();
        $result['result']['technician2']   =     Celini::newORDO('Person', $objMeta->getTechnicianId2())->getName();
        $result['result']['description']   =     nl2br($objMeta->getDescription());
        $result['result']['conclusion']    =     nl2br($objMeta->getConclusion());
        $result['result']['machineName']   =     $objMeta->getMachineName();
        $result['result']['additionalService']   =  $this->buildAdditionalServiceBlock($enumRadType, $radTicketItemId, true);
        $result['result']['created']             =  $objMeta->getCreated();

        $ctlRadResult   =   new C_RadResult();
        $result['result']['radImage']      =    $ctlRadResult->getRadImageHTML($radTicketItemId, false);

        return json_encode($result);
    }
}
?>